#!/usr/bin/env python
#Copyright (c) 2011 Isaac Dawson (WBTS Project)
#Permission is hereby granted, free of charge, to any person obtaining a copy 
#of this software and associated documentation files (the "Software"), to deal 
#in the Software without restriction, including without limitation the rights 
#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
#copies of the Software, and to permit persons to whom the Software is furnished
#to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all
#copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
#THE SOFTWARE.

# Mimic PyMongo(txMongos) WBTSObjectIds for our other storage methods.
# see txmongo._pymongo.objectid
import warnings
import datetime
import threading
import time
import socket
import os
import struct
try:
    import hashlib
    _md5func = hashlib.md5
except:  # for Python < 2.5
    import md5
    _md5func = md5.new

def _machine_bytes():
    """Get the machine portion of an WBTSObjectId.
    """
    machine_hash = _md5func()
    machine_hash.update(socket.gethostname())
    return machine_hash.digest()[0:3]

class WBTSObjectId(object):
    
    _inc = 0
    _inc_lock = threading.Lock()

    _machine_bytes = _machine_bytes()

    def __init__(self, oid=None):        
        if oid is None:
            self.__generate()
        else:
            self.__validate(oid)
    
    def __generate(self):
        """Generate a new value for this WBTSObjectId.
        """
        oid = ""

        # 4 bytes current time
        oid += struct.pack(">i", int(time.time()))

        # 3 bytes machine
        oid += WBTSObjectId._machine_bytes

        # 2 bytes pid
        oid += struct.pack(">H", os.getpid() % 0xFFFF)

        # 3 bytes inc
        WBTSObjectId._inc_lock.acquire()
        oid += struct.pack(">i", WBTSObjectId._inc)[1:4]
        WBTSObjectId._inc = (WBTSObjectId._inc + 1) % 0xFFFFFF
        WBTSObjectId._inc_lock.release()

        self.__id = oid
    
    def generation_time(self):
        """A :class:`datetime.datetime` instance representing the time of
        generation for this :class:`WBTSObjectId`.

        The :class:`datetime.datetime` is always naive and represents the
        generation time in UTC. It is precise to the second.

        .. versionadded:: 1.2
        """
        t = struct.unpack(">i", self.__id[0:4])[0]
        return datetime.datetime.utcfromtimestamp(t)
    generation_time = property(generation_time)

    def __str__(self):
        return self.__id.encode("hex")

    def __repr__(self):
        return "WBTSObjectId('%s')" % self.__id.encode("hex")

    def __cmp__(self, other):
        if isinstance(other, WBTSObjectId):
            return cmp(self.__id, other.__id)
        return NotImplemented

    def __hash__(self):
        """Get a hash value for this :class:`WBTSObjectId`.

        .. versionadded:: 1.1
        """
        return hash(self.__id)